<?php
/**
* @desc Clase para conectarse a un rbdmsactualmente soporta MySQLI y MySql pero es extensible mediante drivers muy facilmente
*/
class Gi_Db {
  /*se lo hace private ya que la instancia debe obtenerse del metodo factory*/
  private static $_adapter = null;
  private function __construct () {
  }
  
  public static function factory ($driver, $host, $db, $port=null, $user=null, $pass=null, $driver_options = null) {
    $driver = explode("_",$driver);
    foreach ($driver as $key => $value) {
      $driver_array[] = strtolower($value);
    }
    switch ($driver[0]) {
      case "pdo" : 
        $dbh = new Gi_Driver_Pdo($driver[1], $host, $db, $port, $user, $pass, $driver_options);
        break;
      case "mysqli" :
        $dbh = new Gi_Driver_Mysqli($driver[0], $host, $db, $port, $user, $pass, $driver_options);
        break;
      case "pgsql" : 
        $dbh = new Gi_Driver_Pgsql($driver[0], $host, $db, $port, $user, $pass, $driver_options);
        break;
      case "mysql" :
        $dbh = new Gi_Driver_Mysql($driver[0], $host, $db, $port, $user, $pass, $driver_options);
        break;
      default :
        throw new Exception("Driver no Disponible");
    }
    self::$_adapter = $dbh;
  return $dbh;
  }
  
  public static function set_adapter ($adapter) {
    self::$_adapter = $adapter;
  } 
  
  public static function get_adapter () {
    if (self::$_adapter !== null)
      return self::$_adapter;
    else 
      throw new Gi_Exception("adaptador no definido");
  }
  
  public static function get_lookup($sql, $do_query = true) {
    if (!$do_query) {
      return false;
    }
    $adapter = self::get_adapter();
    if ($adapter->execute($sql)) {
      $row = $adapter->fetch_assoc();
      if (!$row) {
        return false;
      }
      else {
        if (count($row)>1) {
          return $row;
        }
        else {
          $item = each($row);
          return $item[1];
        }
      }
    }
    else throw new Exception("No se puede ejecutar el query");
  }
  
  public static function get_recordset($sql) {
    $adapter = self::get_adapter();
    if ($adapter->execute($sql)) {
      while ($row = $adapter->fetch_assoc()) {
        $out[] = $row;
      }
    }
    else throw new Gi_Exception("No se puede ejecutar el query");
    return $out;
  }
}